<template>
  <div>
    <!--    卡片视图区域-->
    <el-card>
      <el-row>
        <el-select style="margin-right: 20px" size="small" v-model="selectedCourseId" placeholder="请选择课程"
                   @change="getStudentGrade">
          <el-option
            v-for="item in CourseList"
            :key="item.CourseId"
            :label="item.courseName"
            :value="item.CourseId">
          </el-option>
        </el-select>
        <el-button size="small" type="primary" @click="getStudentGrade">查询</el-button>
        <el-button class="changePercentage" size="small" type="primary" icon="el-icon-edit"
                   @click="newExpFormVisible=true">修改百分比
        </el-button>
      </el-row>
      <el-table
        :data="display"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column
          prop="stuId"
          label="学生学号"
          align="center"
          sortable
          width="160">
        </el-table-column>
        <el-table-column
          prop="userName"
          label="学生姓名"
          align="center"
          sortable
          width="120">
        </el-table-column>
        <el-table-column
          prop="experName"
          label="实验名称"
          align="center"
          sortable
          width="500">
        </el-table-column>
        <el-table-column
          label="学生成绩"
          align="center">
          <el-table-column
            prop="previewScore"
            label="预习成绩"
            align="center"
            sortable
            width="100">
          </el-table-column>
          <el-table-column
            prop="acceptanceScore"
            label="验收成绩"
            align="center"
            sortable
            width="100">
          </el-table-column>
          <el-table-column
            prop="reportScore"
            label="报告成绩"
            align="center"
            sortable
            width="100">
          </el-table-column>
        </el-table-column>
        <el-table-column
          prop="totalScore"
          label="总成绩"
          align="center"
          sortable
          width="100">
        </el-table-column>
      </el-table>
    </el-card>
    <!--    弹出框-->
    <el-dialog title="总成绩计算设置" :visible.sync="newExpFormVisible" @close="chooseExpClosed">
      <el-form ref="tempPercent" :model="tempPercent">
        <el-form-item prop="prescorePercent" size="small" label="预习报告占比" label-width="100px" style="width: 320px">
          <el-input type="number" v-model.number="tempPercent.prescorePercent"></el-input>
        </el-form-item>
        <el-form-item prop="acceptscorePercent" size="small" label="验收报告占比" label-width="100px" style="width: 320px">
          <el-input type="number" v-model.number="tempPercent.acceptscorePercent"></el-input>
        </el-form-item>
        <el-form-item prop="reportscorePercent" size="small" label="报告得分占比" label-width="100px" style="width: 320px">
          <el-input type="number" v-model.number="tempPercent.reportscorePercent"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newExpFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitChooseExp">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      display: [{ // 一定要有一个唯一的id值与row-key绑定，不然无法渲染
        id: Math.random(), // 一定要有，而且是唯一值，不然无法正确刷新
        academy: '电子与光学工程学院、微电子学院',
        acceptanceScore: 70,
        experId: '111',
        experName: 'LCD1602液晶显示器应用',
        major: '光电信息科学与工程',
        previewScore: 80,
        reportId: 4,
        reportScore: 90,
        stuId: 'B17030331',
        userName: '陶永昱'
      }, {
        id: Math.random(),
        academy: '电子与光学工程学院、微电子学院',
        acceptanceScore: 60,
        experId: '111',
        experName: 'LCD1602液晶显示器应用',
        major: '计算机科学与技术',
        previewScore: 90,
        reportId: 10,
        reportScore: 89,
        stuId: 'B17040417',
        userName: '杨龙龙',
        children: [{
          id: Math.random(),
          academy: '电子与光学工程学院、微电子学院',
          acceptanceScore: 98,
          experId: '111',
          experName: 'LCD1602液晶显示器应用2',
          major: '计算机科学与技术',
          previewScore: 50,
          reportId: 10,
          reportScore: 69,
          stuId: 'B17040417',
          userName: '李沛隆'
        }]
      }],
      newExpFormVisible: false,
      // 弹出框的表格
      tempPercent: {
        acceptscorePercent: 0.1,
        prescorePercent: 0.2,
        reportscorePercent: 0.7
      },
      // 三次报告分数总成绩占比，相加要等与1
      acceptscorePercent: 0.1,
      prescorePercent: 0.2,
      reportscorePercent: 0.7,
      StudentGradeShow: [],
      temp: [],
      flag: 0,
      // 后端返回的数据中有哪些学生
      student: [],
      // 学生总数
      totalStudent: 0,
      selectedCourseId: '123', // 选中的课程id
      // 下拉框课程列表
      CourseList: [{ // 课程列表
        CourseId: '2',
        courseName: '电工电子基础实验cccccc'
      }, {
        CourseId: '123',
        courseName: '信息钮原理与应用'
      }, {
        CourseId: '444131',
        courseName: '微控制器应用技术'
      }, {
        CourseId: '333142',
        courseName: '小型智能系统设计'
      }, {
        CourseId: 'a23413',
        courseName: 'RFID原理与应用系统设计'
      }, {
        CourseId: 'B10009023S',
        courseName: 'EDA技术虚拟仿真与远程实验'
      }
      ],
      // 从后端接收总体学生成绩后，进行重组后的用于展示的数据
      // 用于接收直接从后端请求的数据
      StudentGrade: []
    }
  },
  created () {
    this.getStudentGrade()
  },
  methods: {
    test () {
      this.temp = this.display[0]
      console.log(this.temp)
      this.$delete(this.temp, 'userName')
      console.log(this.temp)
    },
    chooseExpClosed () {
      this.$refs.tempPercent.resetFields()
    },
    // 提交表格的验证
    submitChooseExp () {
      // 验证百分比和为1
      if (this.tempPercent.acceptscorePercent + this.tempPercent.prescorePercent + this.tempPercent.reportscorePercent === 1) {
        this.reportscorePercent = this.tempPercent.reportscorePercent
        this.acceptscorePercent = this.tempPercent.acceptscorePercent
        this.prescorePercent = this.tempPercent.prescorePercent
        this.getStudentGrade()
        this.$message.success('设置成功')
        // console.log(this.tempPercent)
        // 设置成功后关闭表格
        this.newExpFormVisible = false
      } else {
        this.$message.error('百分比设置不正确，请确定百分比总和为1')
        // console.log(this.tempPercent)
      }
    },
    async getStudentGradeByCourseId () {
      // const elementById = window.document.getElementById('course')
      // console.log(elementById)
      await this.getStudentGrade()
    },
    async getStudentGrade () {
      const { data: res } = await this.$http.post('/queryAllStuGrade', { courseId: this.selectedCourseId })
      // await this.$http.post('/queryAllStuGrade', { courseId: this.selectedCourseId }) // 使用.then逻辑,存在问题,数据无法获取，舍弃
        // .then(resp => {
        //   console.log('获取学生成绩接口测试')
        //   // 接受后端数据
        //   console.log(resp)
        //   this.StudentGrade = resp.data.data
        //   console.log(this.StudentGrade)
        //   // 对后端数据进行重组以便展示
        //   console.log('获取学生成绩接口测试2')
        //   this.total = this.StudentGradeShow.total
        //   console.log(this.total)
        // })
        .catch((error) => {
          console.log(error)
          this.$message.error('网络连接超时')
        })
      if (res.status !== 200) this.$message.error('获取成绩信息失败')
      // --------------------进行数据重组
      // console.log('获取学生成绩接口测试2')
      // console.log(res.data.data) // 上面有了then方法后data:res不会被赋值，两者二选一
      // 接受后端数据
      this.StudentGrade = res.data.data
      // console.log(this.StudentGrade)
      // 对接收的数据进行重组以便展示
      // 1.得到所有的学生，看是否需要，好像重组不要这个也行
      // this.StudentGrade.forEach((item, i) => {
      //   if (i === 0) this.student[0] = item // 赋初值
      //   else {
      //     // console.log(this.student[this.student.length - 1])
      //     // console.log(this.student[this.student.length - 1] !== '杨龙龙')
      //     if (this.student[this.student.length - 1].userName !== item.userName) {
      //       this.student[this.student.length] = item
      //     }
      //   }
      // })
      // // 根据得到的数据生成展示的数据,flag标志StudentGradeShow中的children位置
      for (let i = 0; i < this.StudentGrade.length; i++) {
        // 给StudentGradeShow装初值,flag标志StudentGradeShow中的children位置
        if (i === 0) {
          this.StudentGradeShow[0] = this.StudentGrade[0]
          // 使用$set方法为其添加id属性,以便表格正常更新，用随机数赋值避免重复
          this.$set(this.StudentGradeShow[this.flag], 'id', Math.random())
          // 使用$set方法为其添加children属性
          this.$set(this.StudentGradeShow[this.flag], 'children', [])
          // 使用数组的push方法为children添加内容
          // this.StudentGradeShow[0].children.push({ take: 'hello' })，下面从i=1开始
        } else if (this.StudentGrade[i].userName === this.StudentGradeShow[this.flag].userName) {
        // 用户名相同时，说明是同一学生，属性统一到该用户的children数组中
          // 将StudentGrade中同一学生的的属性添加到该学生的children属性中,push是添加到最后
          // 添加id属性后将其加到children中
          this.$set(this.StudentGrade[i], 'id', Math.random())
          this.StudentGradeShow[this.flag].children.push(this.StudentGrade[i])
        } else { // 只有在用户不同时会执行，因此只会执行一次，用户名不同时，说明是新的用户
          // StudentGradeShow需要开创一个新的用户组,将标志位+1
          this.flag = this.flag + 1
          this.StudentGradeShow[this.flag] = this.StudentGrade[i]
          // 使用$set方法为新用户添加children属性
          this.$set(this.StudentGradeShow[this.flag], 'id', Math.random())
          this.$set(this.StudentGradeShow[this.flag], 'children', [])
        }
      }
      // console.log(this.StudentGradeShow)
      //  对studentShow进行重组，以便下面平均分的计算
      this.StudentGradeShow.forEach((item) => {
        // 只对有children的用户重组
        if (item.children.length > 0) {
          // 封装对象用于push进数组中
          this.temp =
            {
              id: Math.random(), // 一定要有，而且是唯一值，不然无法正确刷新
              academy: item.academy,
              acceptanceScore: item.acceptanceScore,
              experId: item.experId,
              experName: item.experName,
              major: item.major,
              previewScore: item.previewScore,
              reportId: item.reportId,
              reportScore: item.reportScore,
              stuId: item.stuId,
              userName: item.userName
            }
            // 将得到的temp对象推进数组中，之后便可以进行第一列数据的更新，unshift表示从头推
          item.children.unshift(this.temp)
        }
      })
      // console.log(this.StudentGradeShow)
      // 算出学生各门功课的平均成绩，并更新
      this.StudentGradeShow.forEach((item) => {
        if (item.children.length > 0) {
          let sum1 = 0; let sum2 = 0; let sum3 = 0
          item.children.forEach((item) => {
            sum1 = sum1 + item.acceptanceScore
            sum2 = sum2 + item.previewScore
            sum3 = sum3 + item.reportScore
          })
          // 得到学生各门课的平均成绩,toFixed(2)保留两位小数
          const average1 = (sum1 / item.children.length).toFixed(2)
          const average2 = (sum2 / item.children.length).toFixed(2)
          const average3 = (sum3 / item.children.length).toFixed(2)
          // 将第一列更新为平均成绩
          item.acceptanceScore = average1
          item.previewScore = average2
          item.reportScore = average3
          // 改总的实验名称
          item.experName = item.children[0].experName + '...' + item.children[item.children.length - 1].experName
          // 计算总成绩
          // console.log('测试')
          // console.log(average1 * this.acceptscorePercent)
          this.$set(item, 'totalScore', (average1 * this.acceptscorePercent + average2 * this.prescorePercent + average3 * this.reportscorePercent).toFixed(2))
        } else { // 无children直接算总成绩
          this.$set(item, 'totalScore', (item.acceptanceScore * this.acceptscorePercent + item.previewScore * this.prescorePercent + item.reportScore * this.reportscorePercent).toFixed(2))
        }
      })
      // console.log(this.StudentGradeShow)
      // 清空标志位
      this.flag = 0
      this.display = this.StudentGradeShow
      // 将StudentGradeShow置空，方便下次重组
      this.StudentGradeShow = []
    }
  }
}
</script>

<style scoped>
.changePercentage {
  float: right;
}
.changePercentage{
  float: right;
}
</style>
